package com.javen.controller;

import com.alibaba.fastjson.JSONObject;
import com.javen.model.Car;
import com.javen.model.User;
import com.javen.service.ICarService;
import com.javen.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping({"/car"})
public class CarController {
    private static Logger log = LoggerFactory.getLogger(CarController.class);

    @Resource
    private ICarService carService;

    @Resource
    private IUserService userService;

    @RequestMapping(value = {"/showcars"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET})
    @ResponseBody
    public List<Car> showCarsByUsername(HttpServletRequest request, Model model) {
        String username = request.getParameter("username");
        System.out.println(username);
        User user = new User();
        user = this.userService.getUserByUserName(username);
        String user_id = user.getUserId();
        System.out.println(user_id);
        List<Car> cars = this.carService.showCarsByUserId(user_id);
        log.info(cars.toString());
        return cars;
    }

    @RequestMapping(value = {"/registercar"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public JSONObject registerCar(HttpServletRequest request, Model model) {
        String username = request.getParameter("username");
        String licence_plate = request.getParameter("licence_plate");
        int status = 0;
        User user = new User();
        user = this.userService.getUserByUserName(username);
        String user_id = user.getUserId();
        Car car = new Car();
        car.setUserID(user_id);
        car.setLicencePlate(licence_plate);
        car.setStatus(Integer.valueOf(status));
        JSONObject json = new JSONObject();
        int res = 0;
        try {

            res = this.carService.insertCar(car);

        } catch (Exception e) {

            log.info(e.toString());
        }
        if (res == 1) {
            json.put("res", Integer.valueOf(1));
        } else {
            json.put("res", Integer.valueOf(0));
        }
        return json;
    }
}


